package cn.fenqing168.nio;

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * 从文件读取数据
 * @author fenqing
 */
public class NioFileChannel2 {

    public static void main(String[] args) {

        //创建一个fileinputstream
        try(FileInputStream fis = new FileInputStream("./nio/fileChannel2.txt")){
            //获取一个channel
            FileChannel channel = fis.getChannel();
            //创建一个缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            //读取数据
            StringBuilder sb = new StringBuilder();
            while (channel.read(buffer) > 0) {
                buffer.flip();
                sb.append(new String(buffer.array(), 0, buffer.limit(), StandardCharsets.UTF_8));
                buffer.flip();
            }
            System.out.println(sb);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
